
from sqlalchemy import select, and_
from domain.models.models import UserFav
from domain.models.models import Activity
from domain.models.models import Address
from db.db import async_session
import json

async def create_fav(fav_data):
    """创建收藏
    Args:
        fav_data: 收藏数据，包含以下字段：
            user_id: 用户ID
            activity_id: 活动ID
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            # 检查是否已经收藏
            result = await session.execute(
                select(UserFav).where(
                    and_(
                        UserFav.user_id == fav_data['user_id'],
                        UserFav.activity_id == fav_data['activity_id'],
                        UserFav.is_delete == 0
                    )
                )
            )
            existing_fav = result.scalar_one_or_none()
            
            if existing_fav:
                return False, "已经收藏过该活动"
            
            # 创建新的收藏记录
            fav = UserFav(
                user_id=fav_data['user_id'],
                activity_id=fav_data['activity_id']
            )
            
            session.add(fav)
            await session.commit()
            
            return True, "收藏成功"
            
        except Exception as e:
            await session.rollback()
            return False, str(e)

async def delete_fav(user_id, activity_id):
    """取消收藏
    Args:
        user_id: 用户ID
        activity_id: 活动ID
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            # 查询收藏记录
            result = await session.execute(
                select(UserFav).where(
                    and_(
                        UserFav.user_id == user_id,
                        UserFav.activity_id == activity_id,
                        UserFav.is_delete == 0
                    )
                )
            )
            fav = result.scalar_one_or_none()
            
            if not fav:
                return False, "未找到收藏记录"
            
            # 软删除收藏记录
            fav.is_delete = 1
            await session.commit()
            
            return True, "取消收藏成功"
            
        except Exception as e:
            await session.rollback()
            return False, str(e)

async def get_user_favs(user_id, page, page_size, filters=None):
    """获取用户的收藏列表
    Args:
        user_id: 用户ID
        page: 页码
        page_size: 每页数量
        filters: 筛选条件字典，可包含 type, area, people
    Returns:
        tuple: (是否成功, 结果信息)
    """
    async with async_session() as session:
        try:
            # 构建基础查询条件
            base_conditions = [
                UserFav.user_id == user_id,
                UserFav.is_delete == 0,
                Activity.is_delete == 0
            ]
            
            # 添加筛选条件
            if filters:
                if 'type' in filters:
                    base_conditions.append(Activity.type == filters['type'])
                if 'area' in filters:
                    base_conditions.append(Address.address.like(f"%{filters['area']}%"))
                if 'people' in filters:
                    # 根据人数范围筛选
                    if filters['people'] == '1-3人':
                        base_conditions.append(Activity.people_number <= 3)
                    elif filters['people'] == '3-5人':
                        base_conditions.append(and_(Activity.people_number > 3, Activity.people_number <= 5))
                    elif filters['people'] == '5-10人':
                        base_conditions.append(and_(Activity.people_number > 5, Activity.people_number <= 10))
                    elif filters['people'] == '10人以上':
                        base_conditions.append(Activity.people_number > 10)
            
            # 查询用户的收藏活动，同时关联地址信息
            result = await session.execute(
                select(UserFav, Activity, Address)
                .join(Activity, UserFav.activity_id == Activity.id)
                .join(Address, Activity.address_id == Address.id)
                .where(and_(*base_conditions))
                .offset((page - 1) * page_size)
                .limit(page_size)
            )
            
            favs = []
            for fav, activity, address in result:
                # 解析活动图片列表
                activity_images = json.loads(activity.images) if activity.images else []
                
                favs.append({
                    'id': fav.id,
                    'activity_id': activity.id,
                    'activity_name': activity.name,
                    'activity_content': activity.content,
                    'activity_type': activity.type,
                    'activity_images': activity_images,
                    'activity_fee': activity.fee,
                    'activity_status': activity.status,
                    'activity_start_time': activity.start_time,
                    'activity_end_time': activity.end_time,
                    'activity_people_number': activity.people_number,
                    'activity_people_age': activity.people_age,
                    'created_user_id': activity.created_user_id,
                    'address': {
                        'id': address.id,
                        'name': address.name,
                        'address': address.address,
                        'longitude': address.longitude,
                        'latitude': address.latitude
                    },
                    'created_at': fav.c_time.strftime('%Y-%m-%d %H:%M:%S')
                })
                
            # 获取总数（应用相同的筛选条件）
            total_result = await session.execute(
                select(UserFav)
                .join(Activity, UserFav.activity_id == Activity.id)
                .join(Address, Activity.address_id == Address.id)
                .where(and_(*base_conditions))
            )
            total = len(total_result.all())
            
            return True, {
                'total': total,
                'list': favs
            }
            
        except Exception as e:
            return False, str(e)